package com.example.demo.controller;

import com.example.demo.common.PageResult;
import com.example.demo.common.Result;
import com.example.demo.entity.Book;
import com.example.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * 图书API控制器
 * @author Logan.Li
 */
@RestController
@RequestMapping("/api/books")
@CrossOrigin(origins = "*")
public class BookController {
    
    @Autowired
    private BookService bookService;
    
    /**
     * 获取所有图书（支持分页和全部）
     */
    @GetMapping
    public Result<Object> getAllBooks(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id") String sort,
            @RequestParam(defaultValue = "false") boolean all) {
        
        if (all) {
            // 返回所有图书，不分页
            List<Book> allBooks = bookService.findAll();
            return Result.success(allBooks);
        } else {
            // 分页查询
            Pageable pageable = PageRequest.of(page - 1, size, Sort.by(sort));
            Page<Book> bookPage = bookService.findAll(pageable);
            return Result.success(PageResult.fromPage(bookPage));
        }
    }
    
    /**
     * 根据ID获取图书
     */
    @GetMapping("/{id}")
    public Result<Book> getBookById(@PathVariable Long id) {
        Optional<Book> book = bookService.findById(id);
        return book.map(Result::success)
                .orElseGet(() -> Result.error("图书不存在"));
    }
    
    /**
     * 创建图书
     */
    @PostMapping
    public Result<Book> createBook(@RequestBody Book book) {
        return Result.success(bookService.saveBook(book));
    }
    
    /**
     * 更新图书
     */
    @PutMapping("/{id}")
    public Result<Book> updateBook(@PathVariable Long id, @RequestBody Book book) {
        try {
            Optional<Book> existingBook = bookService.findById(id);
            if (existingBook.isPresent()) {
                book.setId(id);
                // 保留原有的创建时间
                book.setGmtCreate(existingBook.get().getGmtCreate());
                return Result.success(bookService.saveBook(book));
            } else {
                return Result.error("图书不存在");
            }
        } catch (Exception e) {
            return Result.error("更新图书失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除图书
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteBook(@PathVariable Long id) {
        Optional<Book> existingBook = bookService.findById(id);
        if (existingBook.isPresent()) {
            bookService.deleteById(id);
            return Result.success(null);
        } else {
            return Result.error("图书不存在");
        }
    }
    
    /**
     * 根据标题搜索图书
     */
    @GetMapping("/search")
    public Result<List<Book>> searchBooks(@RequestParam String title) {
        List<Book> books = bookService.findByTitle(title);
        return Result.success(books);
    }
    
    /**
     * 根据分类获取图书
     */
    @GetMapping("/category")
    public Result<List<Book>> getBooksByCategory(@RequestParam String category) {
        List<Book> books = bookService.findByCategory(category);
        return Result.success(books);
    }
}
